package utils

import (
	"bytes"
	"encoding/json"
	"reflect"
	"regexp"
	"strconv"
	"strings"
	"text/template"
)

// String 转为int类型
func Int(s string) int {
	if s == "" {
		return 0
	}
	value, err := strconv.Atoi(s)
	if err != nil {
		return 0
	}
	return value
}

func Find(array []interface{}, item interface{}) (index int) {
	index = -1
	for idx, value := range array {
		if value == item {
			index = idx
			break
		}
	}
	return
}

// 解析模板
func Render(data map[string]string, content string) (body string, err error) {
	var buf bytes.Buffer

	if temp, err := template.New("").Option("missingkey=zero").Parse(content); err == nil {
		if err := temp.Execute(&buf, data); err == nil {
			content = buf.String()
			return content, nil
		} else {
			return content, err
		}
	} else {
		return content, err
	}
}

// 查找字符是否在数组中
func InArray(obj interface{}, target interface{}) bool {
	targetValue := reflect.ValueOf(target)
	switch reflect.TypeOf(target).Kind() {
	case reflect.Slice, reflect.Array:
		for i := 0; i < targetValue.Len(); i++ {
			if targetValue.Index(i).Interface() == obj {
				return true
			}
		}
	case reflect.Map:
		if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {
			return true
		}
	}

	return false
}

func CamelCaseToSnakeCase(str string) string {
	if str == "" {
		return str
	}
	strLen := len(str)
	result := make([]byte, 0, strLen*2)
	j := false
	for i := 0; i < strLen; i++ {
		char := str[i]
		if i > 0 && char >= 'A' && char <= 'Z' && j {
			result = append(result, '_')
		}
		if char != '_' {
			j = true
		}
		result = append(result, char)
	}
	str = strings.ToLower(string(result))
	return str
}

func MarshalJSON(v interface{}) []byte {
	// Regexp definitions
	var keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`)
	var wordBarrierRegex = regexp.MustCompile(`(\w)([A-Z])`)
	marshalled, err := json.Marshal(v)
	if err != nil {

	}
	converted := keyMatchRegex.ReplaceAllFunc(
		marshalled,
		func(match []byte) []byte {
			return bytes.ToLower(wordBarrierRegex.ReplaceAll(
				match,
				[]byte(`${1}_${2}`),
			))
		},
	)
	return converted
}

func GetMobileEncrypt(mobile string) string {
	if len(mobile) > 7 {
		return mobile[:3] + "****" + mobile[7:]
	} else if len(mobile) > 3 {
		return mobile[:3] + "****"
	}
	return mobile
}
func GetContactNameEncrypt(name string) string {
	first := string([]rune(name)[0:1])
	return first + "**"
}
